
package cn.yunyichina.provider.clinic.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class OrderNoGenerator {
	private static Logger logger = LoggerFactory.getLogger(OrderNoGenerator.class);
	
	private static final String COVER_CHAR = "0";

	private static AtomicLong serialNumGen = new AtomicLong(0);

	private static DateFormat df = new SimpleDateFormat("yyyyMMddHHmm");

	private static DateFormat simpleDf = new SimpleDateFormat("yyyyMMdd");

	/**
	 * 订单固定前缀
	 */
	private static final String ORDER_PREFIX = "Y";

	/**
	 * 订单日期标志位  判断流水号是否需要从1开始
	 */
	private static long orderDay;

	private static Byte lockObj = new Byte("0");

	private static int serverNo;

	static {
		orderDay = Long.valueOf(simpleDf.format(new Date()));
		//根据服务器的MAC地址生成1-9的编号
		InetAddress address;
		try {
			address = InetAddress.getLocalHost();
			NetworkInterface ni = NetworkInterface.getByInetAddress(address);
			byte[] mac = ni.getHardwareAddress();
			String sMAC = null;
			Formatter formatter = new Formatter();
			for (int i = 0; i < mac.length; i++) {
				sMAC = formatter.format(Locale.getDefault(), "%02X%s", mac[i], ( i < mac.length - 1 ) ? "-" : "").toString();
			}
			if (StringUtils.isBlank(sMAC)) {
				sMAC = address.getHostAddress();
			}
			serverNo = ( Math.abs(sMAC.hashCode()) % 9 + 1 );
		} catch (Exception e) {
			// TODO Auto-generated catch block
			serverNo = 1;
		}
	}

	
	public static String genOrderNo(int orderType, int tradeType, int bizType) {
		if (orderType != 0 && tradeType != 0 && bizType != 0) {
			StringBuffer sb = new StringBuffer();

			sb.append(ORDER_PREFIX);
			logger.info("orderType===="+orderType);
			sb.append(orderType);

			//日期前缀
			sb.append(df.format(new Date()));

			//支付类型前缀
			sb.append(tradeType);

			//业务类型前缀
			if (bizType > 10) {
				sb.append(bizType);
			} else {
				sb.append(COVER_CHAR + bizType);
			}

			//服务器编号
			sb.append(serverNo);

			//流水号
			long nowDay = Long.valueOf(simpleDf.format(new Date()));
			if (nowDay > orderDay) {
				synchronized (lockObj) {
					if (nowDay > orderDay) {
						orderDay = nowDay;
						serialNumGen = new AtomicLong(0);
					}
				}
			}
			String serialNum = String.valueOf(serialNumGen.incrementAndGet());

			/**
			 * modify by 由于某些医院长度限制  故不补位
			 * 去除前1位  因为为了避免补位的麻烦  是以7位数1000000为起始值
			 * serialNum = serialNum.substring(1);
			 */
			sb.append(serialNum);

			return sb.toString();
		} else {
			return null;
		}
	}
}
